package net.bblbs.zhongrx.util;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.UserDictionary;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.bumptech.glide.Glide;

import net.bblbs.zhongrx.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileStoreUtil {
    private static String TAG = "ZRX_FileStoreUtil";

    private static final String JPEG_FILE_PREFIX = "IMG_";
    private static final String JPEG_DYN_FILE_PREFIX = "IMG_DYN_";
    private static final String JPEG_FILE_SUFFIX = ".jpg";

    private static final String VIDEO_FILE_PREFIX = "VID_";
    private static final String VIDEO_DYN_FILE_PREFIX = "VID_DYN_";
    private static final String VIDEO_FILE_SUFFIX = ".mp4";

    private static final String ALBUM_NAME = "ZRX";

    public static File getAlbumDir(String personId, Context context) {
        File storageDir = null;

        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            storageDir = new File(context.getExternalFilesDir(null),ALBUM_NAME + "/"+ personId);
            Log.d(TAG, "storageDir: " + storageDir.getAbsolutePath());
            if (storageDir != null) {
                if (! storageDir.exists()) {
                    if (! storageDir.mkdirs()){
                        Log.d(TAG, "failed to create directory");
                        return null;
                    }
                }

                File nomedia = new File(storageDir, ".nomedia");
                boolean exists = nomedia.exists();
                try {
                    if (!exists){
                        boolean created = nomedia.createNewFile();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG, "failed to create nomedia");
                }
            }
        } else {
            Log.d(TAG, "External storage is not mounted READ/WRITE.");
        }
        return storageDir;
    }

    public static void deleteFiles(String personId, Context context) {
        File storageDir = null;

        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            storageDir = new File(context.getExternalFilesDir(null), ALBUM_NAME + "/" + personId);
            String[]  myFiles = storageDir.list();
            if (myFiles ==null){
                return;
            }
            for (int i=0; i<myFiles.length; i++) {
                File myFile = new File(storageDir, myFiles[i]);
                myFile.delete();
            }
            storageDir.delete();
        }else {
            Log.d(TAG, "External storage is not mounted READ/WRITE.");
        }

    }

    public static File setUpPhotoFile(String personId, String fileID, Context context) throws IOException {
        String imageFileName = fileID +"_";
        File albumF = getAlbumDir(personId, context);
        File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
        Log.d(TAG, "currentPhotoPath: " + imageF.getAbsolutePath());
        return imageF;
    }

//    public static File setUpDynPhotoFile(String personId, int actionID, Context context) throws IOException {
//        String imageFileName = JPEG_DYN_FILE_PREFIX + actionID +"_";
//        File albumF = getAlbumDir(personId, context);
//        File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
//        Log.d(TAG, "currentDynPhotoPath: " + imageF.getAbsolutePath());
//        return imageF;
//    }

    public static File setUpVideoFile(String personId, int actionID, Context context) throws IOException{
        String videoFileName = VIDEO_FILE_PREFIX + actionID +"_";
        File albumF = getAlbumDir(personId, context);
        File videoF = File.createTempFile(videoFileName, VIDEO_FILE_SUFFIX, albumF);
        Log.d(TAG, "currentVideoPath: " + videoF.getAbsolutePath());
        return videoF;
    }

    public static File setUpDynVideoFile(String personId, int actionID, Context context) throws IOException{
        String videoFileName = VIDEO_DYN_FILE_PREFIX + actionID +"_";
        File albumF = getAlbumDir(personId, context);
        File videoF = File.createTempFile(videoFileName, VIDEO_FILE_SUFFIX, albumF);
        Log.d(TAG, "currentDynVideoPath: " + videoF.getAbsolutePath());
        return videoF;
    }

    //not required for the current device
//    public static void deleteLastFromDCIM(Context context) {
//        String[] projection = { MediaStore.Images.Media._ID };
//
//        try {
//            File[] images = new File(Environment.getExternalStorageDirectory()
//                    + File.separator + "DCIM/Camera").listFiles();
//            File latestSavedImage = images[0];
//            for (int i = 1; i < images.length; ++i) {
//                if (images[i].lastModified() > latestSavedImage.lastModified()) {
//                    latestSavedImage = images[i];
//                }
//            }
//
//            Log.d(TAG, "deleteLastFromDCIM: " + latestSavedImage.getAbsoluteFile());
//
//
//            // Match on the file path
//            String selection = MediaStore.Images.Media.DATA + " = ?";
//            String[] selectionArgs = new String[] { latestSavedImage.getAbsolutePath() };
//
//            // Query for the ID of the media matching the file path
//            Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
//
//            ContentResolver contentResolver = context.getContentResolver();
//            Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
//            if (c.moveToFirst()) {
//                // We found the ID. Deleting the item via the content provider will also remove the file
//                long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
//                Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
//                contentResolver.delete(deleteUri, null, null);
//            } else {
//                // File not found in media store DB
//            }
//            c.close();
//
////          another way to remove photo from gallery
////            if (latestSavedImage.exists()) {
////                if (latestSavedImage.delete()) {
////                    Log.e("-->", "file Deleted :" + latestSavedImage);
////                    callBroadCast(context);
////                } else {
////                    Log.e("-->", "file not Deleted :" + latestSavedImage);
////                }
////            }
//        } catch (Exception e) {
//            Log.e(TAG, "exception: " + e.toString());
//            e.printStackTrace();
//        }
//
//    }
//
//    public static void callBroadCast(Context context) {
//        if (Build.VERSION.SDK_INT >= 14) {
//            Log.e("-->", " >= 14");
//            MediaScannerConnection.scanFile(context, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
//                public void onScanCompleted(String path, Uri uri) {
//                    Log.e(TAG, "Scanned " + path + ":");
//                    Log.e(TAG, "-> uri=" + uri);
//                }
//            });
//        } else {
//            Log.e("-->", " < 14");
//            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
//                    Uri.parse("file://" + Environment.getExternalStorageDirectory())));
//        }
//    }


//    public static boolean existsTmpFile(String personId, Context context) {
//
//        File storageDir = null;
//
//        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//            storageDir = new File(context.getExternalFilesDir(null), ALBUM_NAME + "/" + personId);
//            String[]  myFiles = storageDir.list();
//            if (myFiles ==null){
//                return false;
//            }
//            for (int i=0; i<myFiles.length; i++) {
//                File myFile = new File(storageDir, myFiles[i]);
//                if (myFile.toString().contains(".mp4.mp4")){
//                    return true;
//                }
//            }
//        }else {
//            Log.d(TAG, "External storage is not mounted READ/WRITE.");
//        }
//
//        return false;
//    }


//    public static boolean existsTmpPrevFile(int ordinal, String personId, Context context) {
//
//        File storageDir = null;
//
//        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//            storageDir = new File(context.getExternalFilesDir(null), ALBUM_NAME + "/" + personId);
//            String[]  myFiles = storageDir.list();
//            if (myFiles ==null){
//                return false;
//            }
//            for (int i=0; i<myFiles.length; i++) {
//                File myFile = new File(storageDir, myFiles[i]);
//                if ((myFile.toString().contains(".mp4.mp4")) && (myFile.toString().contains("VID_"+ordinal + "_")) )  {
//                    return true;
//                }
//            }
//        }else {
//            Log.d(TAG, "External storage is not mounted READ/WRITE.");
//        }
//
//        return false;
//    }

    public static void deleteOldFile(String filePath){
        if (!TextUtils.isEmpty(filePath)){
            File file = new File(filePath);
            boolean deleted = file.delete();
            Log.d(TAG, "delete file: "+ filePath);
        }
    }

    public static double copyFile(InputStream inputStream, FileOutputStream outputStream) {
        int read = 0;
        byte[] bytes = new byte[1024*1024];
        double count = 0;
        try {
            while ((read = inputStream.read(bytes)) != -1) {
                count ++;
                outputStream.write(bytes, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return count;
    }

    private void downloadFile(String url, String personId, int ordinal,final ImageView imageView, final Activity activity){
        HttpRequest.downloadFile(url
            , personId
            , ordinal
            ,new HttpCallbackListener() {
                @Override
                public void onFinish(final String response) {

                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d(TAG, "downloaded");
                            Glide.with(activity).load(response).into(imageView);

                        }
                    });
                }

                @Override
                public void onError(Exception e) {
                    Log.d(TAG, "onError: " + e.toString());
                }
            }
        );
    }

}
